const loadRouter = require('./routes')

const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
var error = require('koa-json-error')
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const context = require('./src/config/context')
const Koa_Session = require('koa-session');
const { koaSwagger } = require('koa2-swagger-ui')
const swagger = require('./src/config/swagger')// 存放swagger.js的位置，可以自行配置，我放在了根目录
// error handler
onerror(app);

app.use(async(ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', ctx.headers.origin);// '*'有可能会问题
  ctx.set('Access-Control-Allow-Credentials', 'true');
  ctx.set('Access-Control-Allow-Headers', 'X-Requested-With');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  await next();
});
// 在谷歌浏览器上运行使用了session却失效的坑 https://blog.csdn.net/mus123/article/details/113473765
const SESSION_CONFIG = {
  // resave: false, // 强制保存，如果session没有被修改也要重新保存
  // saveUninitialized: true, // 如果原先没有session那么久设置，否则不设置
  // cookie: {
  //   secure: true
  // },
  key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  overwrite: true,
  /** (boolean) can overwrite or not (default true) */
  httpOnly: true,
  /** (boolean) httpOnly or not (default true) */
  signed: true,
  /** (boolean) signed or not (default true) */
  rolling: false,
  /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false) */
};
app.keys = ['some secret hurr'];
app.use(Koa_Session(SESSION_CONFIG, app));

// context binding...
Object.keys(context).forEach(key => {
  app.context[key] = context[key] // 绑定上下文对象
})
// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}));

// logger
app.use(async(ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
loadRouter(app)
// 接口文档配置
app.use(swagger.routes(), swagger.allowedMethods())
app.use(koaSwagger({
  routePrefix: '/swagger', // 接口文档访问地址
  swaggerOptions: {
    url: '/swagger.json' // example path to json 其实就是之后swagger-jsdoc生成的文档地址
  }
}))
// error-handling
// app.on('error', (err, ctx) => {
//   console.error('server error', err, ctx);
// });
// 错误处理中间件
app.use(error({
  // 在生产环境下不显示错误堆栈信息，在开发环境下显示错误堆栈信息
  // postFormat定制返回格式
  postFormat: (e, {
    stack,
    ...rest
  }) => {
    return process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
  }
}))

module.exports = app;
